<?php
namespace app\admin\controller;
use think\Db;
use Env;
use PHPExcel_IOFactory;
use think\facade\Request;
use app\admin\model\Department as thisModel;
class Department extends Common
{
    function index(){
        $thisModel = new thisModel();
        $list = $thisModel->mainAllList();

        $this->assign('list',$list);
        return $this->fetch('index');
    }

    function mainEdit(){
        if (request()->isAjax()) {
            $postData = input('post.');
            $id = input('post.id');
            $data['department'] = $postData['department'];
            $data['department_code'] = $postData['department_code'];
//            dump($data);exit;
            if($id > 0){
                $res = Db::name('department')->where("id",$id)->update($data);
                if($res !== false){
                    exitjson(1, '保存成功');
                }else{
                    exitjson(0, '保存失败');
                }
            }else{
                $res = Db::name('department')->insertGetId($data);
                if ($res) {
                    exitjson(1, '保存成功');
                } else {
                    exitjson(0, '保存失败');
                }
            }
        } else {
            if(input('id') > 0){
                $one = Db::name('department')->find(input('id'));
                $this->assign('one',$one);
            }
//            dump($one);exit;
            return $this->fetch('mainEdit');
        }
    }

    function mainDel(){
        $id = input('id');
        if($id>0){
            $thisModel = new thisModel();
            $one = $thisModel->get($id);
            $res = $one->delete();
            if($res !== false){
                exitjson(1,'删除成功');
            }else{
                exitjson(0,'删除失败');
            }
        }
    }

    //导入表格
    public function importExcel(){
        header("content-type:text/html;charset=utf-8");
        // dump($_FILES);
        if (empty ($_FILES ['file'] ['name'])){
            exitjson(0,'请选择文件');
        }
        $file_types = explode(".", $_FILES ['file'] ['name']);
        $file_type = $file_types [count($file_types) - 1];
        // dump($file_type);
        /*判别是不是.xls文件，判别是不是excel文件*/
        if (strtolower($file_type) != "xlsx" && strtolower($file_type) !="xls") {
            // $this->error('不是Excel文件，重新上传');
            exitjson(0,'不是Excel文件，重新上传');
        }
        //上传excel文件
        $file = request()->file('file');
        //将文件保存到public/uploads目录下面
        $info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( 'userfiles/files/');
        if($info){
            //获取上传到后台的文件名
            $fileName = $info->getSaveName();
            //获取文件路径
            $filePath = Env::get('root_path').'userfiles'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.$fileName;
            //获取文件后缀
            $suffix = $info->getExtension();
            //判断哪种类型
            if($suffix=="xlsx"){
                $reader = \PHPExcel_IOFactory::createReader('Excel2007');
                }else{
                $reader = PHPExcel_IOFactory::createReader('Excel5'); 
                }
            }else{
                // $this->error('文件过大或格式不正确导致上传失败-_-!');
                exitjson(0,'文件过大或格式不正确导致上传失败-_-!');
            }
        //载入excel文件
        $excel = $reader->load("$filePath",$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();
        $data = []; //数组形式获取表格数据
        for ($i=2; $i <=$row_num; $i++) { 
            $data[$i]['department_code'] = $sheet->getCell("A".$i)->getValue();
            $data[$i]['department'] = $sheet->getCell("B".$i)->getValue();
            $data[$i]['is_del'] = 0;
            $data[$i]['sort_order'] = 99;
            //将数据保存到数据库
            $department = Db::name('department')->where('department_code',$data[$i]['department_code'])->find();
            if($department){
                unset($data[$i]);  //如果学员账号存在，unset掉
            }
        }
        dump($data);exit;
        $res = Db::name('department')->insertAll($data);
        if($res){
//          unlink($filePath);
            exitjson(1,'导入成功');
        }else{
            exitjson(0,'导入失败');
        }

    }
}